# -*- coding: utf-8 -*-
from functools import partial

from sqlalchemy.exc import IntegrityError

from common.lottery import LOTTERY_TYPE
from common.lottery.cyclical.abstract import activity as base
from common.lottery.cyclical.ssc.order import ssc_calc_miss
from common.utils.decorator import sql_wrapper

fullfill_result = sql_wrapper(
    partial(base.fullfill_result, LOTTERY_TYPE.FF_SSC))

get_latest_term = sql_wrapper(
    partial(base.get_latest_term, LOTTERY_TYPE.FF_SSC))

get_activity_by_term = sql_wrapper(
    partial(base.get_activity_by_term, LOTTERY_TYPE.FF_SSC))

stop_term = sql_wrapper(
    partial(base.stop_term, LOTTERY_TYPE.FF_SSC))

create_new_term = sql_wrapper(
    partial(base.create_new_term, LOTTERY_TYPE.FF_SSC))

get_stats_by_term = sql_wrapper(
    partial(base.get_stats_by_term, LOTTERY_TYPE.FF_SSC))

get_activity_stats = sql_wrapper(
    partial(base.get_activity_stats, LOTTERY_TYPE.FF_SSC))


def calc_miss(trend, save, number, last_stats):
    ssc_calc_miss(trend, save, number, last_stats)

    def calc_func(last, i):
        return str(int(last[i]) + 1) if last[i] != 'x' else 'x'

    # 组选
    config = {
        'miss_5': -2,
        'miss_6': -3,
    }
    for k, v in config.iteritems():
        last = getattr(last_stats, k).split(',')
        hit = number[v:]
        for i in xrange(len(last)):
            last[i] = calc_func(last, i)
        for x in hit:
            last[int(x)] = '0'
        if 'x' in last:
            save = False
        setattr(trend, k, ','.join(last))

    # 大小单双
    hit = number[-2:]
    lasts = last_stats.miss_10.split('|')
    currents = [['0', '0', '0', '0']] * 2

    for i, v in enumerate(lasts):
        current = currents[i]
        last = lasts[i].split(',')
        if int(hit[i]) >= 5:  # 大
            current[1] = calc_func(last, 1)
        else:
            current[0] = calc_func(last, 0)
        if int(hit[i]) % 2 == 0:  # 双
            current[2] = calc_func(last, 2)
        else:
            current[3] = calc_func(last, 3)
        if 'x' in current:
            save = False

    trend.miss_10 = '|'.join([','.join(k) for k in currents])

    # 二星组选和值
    hit = int(number[-1]) + int(number[-2])
    last = last_stats.miss_11.split(',')
    for i in xrange(len(last)):
        last[i] = calc_func(last, i)
    last[hit] = '0'
    if 'x' in last:
        save = False
    trend.miss_11 = ','.join(last)
    return trend, save


@sql_wrapper
def insert_stats(term, number, last_stats):
    trend, index_save = base.generate_trend(LOTTERY_TYPE.FF_SSC, term, number, last_stats)
    print('trend: %s, save: %s' % (trend.as_dict(), index_save))
    trend, bet_type_save = calc_miss(trend, index_save, number, last_stats)
    print('miss: %s, save: %s' % (trend.as_dict(), bet_type_save))

    if index_save:
        try:
            trend.save()
        except IntegrityError:
            pass
    return trend
